package TCPUpFileImage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    public static void main(String[] args) throws Exception {
        int port = 8888;
        // 创建一个serversocket
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("服务启动成功，等待客户端连接...");

        // 使用while循环来处理多个客户端连接
        while (true) {
            Socket acceptSocket = serverSocket.accept();
            System.out.println("与客户端建立连接...");

            // 为每个客户端连接创建一个新的线程来处理文件接收
            new Thread(() -> {
                try {
                    InputStream inputStream = acceptSocket.getInputStream();
                    // 存放文件路径
                    String filePath = "C:\\Users\\Administrator\\Desktop\\2\\2.gif";
                    File file = new File(filePath);
                    try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
                        int byteRead;
                        byte[] buffer = new byte[1024 * 8];
                        while ((byteRead = inputStream.read(buffer)) != -1) {
                            fileOutputStream.write(buffer, 0, byteRead);
                        }
                        System.out.println("文件接收成功！");
                    } catch (IOException e) {
                        System.out.println("文件写入错误：" + e.getMessage());
                    }
                } catch (IOException e) {
                    System.out.println("客户端连接错误：" + e.getMessage());
                } finally {
                    try {
                        acceptSocket.close();
                    } catch (IOException e) {
                        System.out.println("关闭客户端连接错误：" + e.getMessage());
                    }
                }
            }).start();
        }

        // 注意：serverSocket.close() 在这里不再需要，因为服务器应该持续运行
    }
}